<template>
  <div>
    <el-form ref="deptForm" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="obj in list"
            :key="obj.id"

            :value="obj.username"
            :label="obj.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getEmployeeSimple } from '@/api/employees' // 获取员工信息
import { addDepartments, getDepartDetail, updateDepartments } from '@/api/departments' // 新增部门 , 获取部门信息  ,更新部门详情
export default ({
  props: {
    // 点击的那个频道
    id: {
      type: String,
      required: true
    },
    // 打开的是添加还是编辑
    isEdit: {
      type: Boolean,
      require: true
    },
    // 验证时需要的数据
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 验证部门code
    const validCode = (rule, value, callback) => {
      // console.log(rule, value)
      // console.log(this.originList)
      // 获取验证数据中的code
      let existCodeList = this.originList.map(item => item.code)
      // 如果isEdit 是true(编辑状态) 就把把自身的code 排除出去在去验证code 是否重复
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => {
          item.id !== this.id && existCodeList.map(item => item.code)
        })
      }
      // console.log(existCodeList)
      // 验证表单 existCodeList中是否有 value 的值  如果有就执行第一个  没有执行第二个
      existCodeList.includes(value) ? callback(new Error('部门编码存在')) : callback()
    }
    // 验证部门名称
    const validName = (rule, value, callback) => {
      // 查找出演示数据中当前元素pid相同的元素 并取出他们的部门名称
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      if (this.isEdit) {
        // 找出现在被点击元素的id
        const deps = this.originList.find(item => item.id === this.id)

        // 找出父元素
        console.log(deps)
        const pid = deps.pid
        // console.log(pid)
        // 找出pid 相同的兄弟元素的名字
        existNameList = this.originList.filter(item => item.pid === pid && item.id !== this.id).map(item => item.name)
        // console.log(existNameList)
      }
      // console.log(existNameList)
      // 如果value的值在 pid相同的元素中以存在执行if 否则 执行else
      if (existNameList.includes(value)) {
        callback(new Error('当前部门中以存在' + value + '部门'))
      } else {
        callback()
      }
      // console.log(existNameList)
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      list: [],
      rules: {
        name: [
          { required: true, message: '部门名称要求4-50个字符', trigger: 'blur' },
          { min: 3, max: 50, message: '部门名称要求4-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门名称要求4-50个字符', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求4-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadEmployee()
    this.loadDetail()
  },
  methods: {
    // 获取员工信息
    async  loadEmployee() {
      const res = await getEmployeeSimple()
      //   console.log(res.data)
      this.list = res.data
    },
    // 新增部门
    async doAdd() {
      const res = await addDepartments({ ...this.form, pid: this.id })
      this.$emit('update-depart')
      console.log(res)
    },
    // 获取当前部门的详情
    async loadDetail() {
      if (this.isEdit) {
        // alert('现在是编辑，要去获取详情')
        const res = await getDepartDetail(this.id)
        console.log('现在是编辑，要去获取详情', res)
        this.form = res.data
      }
    },
    // 更新部门详情
    async doEdit() {
      try {
        await updateDepartments(this.form)
        this.$message({ type: 'success', message: '修改成功' })
        this.$emit('update-depart')
      } catch (err) {
        console.log(err)
        this.$message({ type: 'error', message: err })
      }
    },
    // 提交
    hSubmit() {
      //  // 如果isEdit 是true 执行 loadDetail 编辑  否则 执行新增
      // this.isEdit ? this.doEdit() : this.doAdd()
      this.$refs.deptForm.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 取消
    hCancel() {
      this.$emit('close')
    }
  }

})

</script>
